package com.cqyc.shop.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@WebServlet(urlPatterns="/download.do")
public class DownloadServlet extends HttpServlet{
	private static final long serialVersionUID = -2761616212745213380L;
	private  Logger logger = LoggerFactory.getLogger(getClass());
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.debug("文件上传到界面");
		
		String filename = request.getParameter("filename");
		String path ="D:/mywork";
		try { 
			if(filename != null && filename.trim().length() > 0) {
				logger.info("读取文件名:{}{}",path,filename);
				response.setContentType("image/png");
				OutputStream out =response.getOutputStream();
				InputStream in = new FileInputStream(new File(path+filename));//打开文件流
				//读取输入文件流的内容，然后
				byte data[] = new byte[4096];// 缓冲字节数
					int size = 0;
					size = in.read(data);
					while(size != -1) {
						out.write(data,0,size);
						size = in.read(data);
					}
					in.close();
					out.flush();
					out.close();
					logger.debug("文件读取成功");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("读取图片文件错误:",e.getMessage());
		}
	}
	
	
	
}
